package com.zt.rongda.companyIncome.service;

import org.springframework.stereotype.Service;

import com.zt.servlet.ReqBean;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class CompanyIncomeAnalyzeService extends BaseService {

	/**
	 * 企业收入分析
	 *
	 * @param reqBean
	 * @return
	 */
	public JSONObject analyze(String payRollYear, String payRollMonth) {
		String dataCondition_start = payRollYear + "-01";
		String dataCondition_end = payRollYear + "-12";
		if (!StringUtil.isEmpty(payRollMonth)) {
			int mount_start = Integer.valueOf(payRollMonth);
			int mount_end = Integer.valueOf(payRollMonth) + 1;
			String payRollMonth_start = Integer.valueOf(mount_start) > 10 ? String.valueOf(mount_start) : "0" + mount_start;
			String payRollMonth_end = Integer.valueOf(mount_end) > 10 ? String.valueOf(mount_end) : "0" + mount_end;
			dataCondition_start = payRollYear + "-" + payRollMonth_start;
			dataCondition_end = payRollYear + "-" + payRollMonth_end;
		}
		JSONObject resultJson = new JSONObject();
		SqlBuilder sql = new SqlBuilder("select  sum(aws.AMOUNT) as totalAmount,aws.AD_ORDER_ID,ao.ORDER_ID,ao.C_ORDER_TYPE,");
		sql.appendSql(" (SELECT c.CODE_NAME FROM SYS_CODE c WHERE c.CODE_TYPE = 'order_type' AND c.CODE_VALUE = ao.C_ORDER_TYPE ) AS orderTypeName");
		sql.appendSql(" from AD_WORKBILL_SETTLEMENT aws LEFT JOIN AD_ORDER ao on aws.AD_ORDER_ID=ao.ORDER_ID");
		sql.appendSql(" where aws.SETTLEMENT_DATE> ? and aws.SETTLEMENT_DATE< ? ");
		sql.appendSql(" GROUP BY ao.C_ORDER_TYPE", dataCondition_start, dataCondition_end);

		JSONArray dataArray = this.query(sql);
		JSONArray resultDataArray = new JSONArray();
		for (int i = 0; i < dataArray.size(); i++) {
			JSONObject data = dataArray.getJSONObject(i);
			String orderTypeName = data.getString("orderTypeName");
			double amount = data.getDouble("totalAmount");
			JSONObject json = new JSONObject();
			json.put("name", orderTypeName);
			json.put("y", amount);
			resultDataArray.add(json);
			resultJson.put("resultDataArray", resultDataArray);
		}
		return resultJson;
	}
}